package com.example.controller;

import com.example.common.Result;
import com.example.entity.PageBean;
import com.example.entity.Worker;
import com.example.service.WorkerService;
import com.example.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class WorkerController {
    @Autowired
    private WorkerService workerService;

    @PostMapping("/login")
    public Result login(@RequestBody Worker worker) {
        log.info("登录的用户为：{}", worker);
        Worker w = workerService.login(worker);
        if (w != null) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", w.getWorkerId());
            String jwt = JwtUtils.generateJwt(claims);
            Map<String, Object> data = new HashMap<>();
            data.put("token", jwt);
            return Result.success(data);
        } else {
            return Result.error("用户名或密码错误！");
        }
    }

    @GetMapping("/info")
    public Result getuUserinfo(@RequestParam("token") String token) {
        Map<String, Object> data = workerService.getuUserinfo(token);
        if (data != null) {
            return Result.success(data);
        }
        return Result.error("token出错");
    }

    @PostMapping("/logout")
    public Result logout() {
        return Result.success("退出成功！");
    }
    @GetMapping("/worker")
    public Result page(@RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer pageSize, String name) {
        PageBean pageBean = workerService.page(page, pageSize, name);
        log.info("分页查询的参数：{}，{}，{}", page, pageSize, name);
        return Result.success(pageBean);
    }

    //驼峰命名法w_name无法实现映射，
    @PostMapping("/worker")
    public Result add(@RequestBody Worker worker) {

        log.info("添加员工的信息为：{}", worker);
        workerService.add(worker);
        return Result.success();
    }

    @DeleteMapping("/worker/{ids}")
    public Result delete(@PathVariable List<Integer> ids) {
        log.info("要删除员工的id为：{}", ids);
        workerService.delete(ids);
        return Result.success();
    }

    @GetMapping("/worker/{id}")
    public Result findById(@PathVariable Integer id) {
        log.info("查找员工的id为：{}", id);
        Worker worker = workerService.findById(id);
        return Result.success(worker);
    }

    @PutMapping("/worker")
    public Result updata(@RequestBody Worker worker) {
        log.info("更新的员工信息为：{}", worker);
        workerService.updata(worker);
        return Result.success();
    }

}
